package com.iflytek.cosmo.ocr.common.config;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 加载示例文件类
 * 
 * @author dgyu
 *
 */
@Configuration
@ConditionalOnClass(PropertyResolver.class)
public class ExampleFileConfig {
	private static final Logger logger = LoggerFactory.getLogger(ExampleFileConfig.class);
	
	//1歪斜校正&自动旋转 2图像切边 3分栏切分 4手印 5签章
	private static final String array_str = "{\"倾斜\":1,\"歪斜\":1,\"分栏\":3,\"黑边\":2,\"手印\":4,\"签章\":4,\"表格\":5,\"印章\":4}";


	@Bean
	public ExampleFileByteConfig buildExamplePicConfig() throws Exception {

		logger.info("############加载系统示例文件开始############");
		ExampleFileByteConfig config = new ExampleFileByteConfig();

		ClassPathResource defaultFldmlb = new ClassPathResource("exampleFile/examplePic.txt");
		InputStream is = defaultFldmlb.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String data = null;
		while ((data = br.readLine()) != null) {
			this.loadFromInnerJar(config, data);
		}

		br.close();
		isr.close();
		is.close();
		@SuppressWarnings("unchecked")
		HashMap<String, Integer> hashMap = JSON.parseObject(array_str, HashMap.class);
		config.setHashMap(hashMap);
		logger.info("############加载系统示例文件结束############");
		return config;
	}

	private void loadFromInnerJar(ExampleFileByteConfig config, String data) {
		String fileResourcePath = "exampleFile/" + data;
		logger.info("加载示例文件" + fileResourcePath);
		ClassPathResource pic = new ClassPathResource(fileResourcePath);
		if (null != pic) {
			try (InputStream picStream = pic.getInputStream()) {
				if (null == picStream) {
					return;
				}
				MultipartFile file = new MockMultipartFile(data, data, ContentType.APPLICATION_OCTET_STREAM.toString(),
						picStream);
				config.add(file);
			} catch (Exception e) {
				logger.error("加载示例文件:{} 异常,异常消息:{}", fileResourcePath, e);
			}
		}

	}

	public static void main(String[] args) throws Exception {
		ExampleFileConfig config = new ExampleFileConfig();
		config.buildExamplePicConfig();
	}
}
